<template>
  <page-header-wrapper :content="$t('task.about')">
    <!-- extra for heading -->
    <div class="extra-content" slot="extraContent">
      <a-button size="small" @click="openSearchForm">
        <a-icon type="search" />
        {{ $t('action.search') }}
      </a-button>
      <a-button size="small" type="primary" @click="openAddForm">
        <a-icon type="plus" />
        {{ $t('action.add') }}
      </a-button>
    </div>

    <!-- drawer for add -->
    <a-drawer width="650" :title="$t('task.form.add.title')" :visible="addFormVisible" @close="closeAddFrom">
      <AddTask :origin="addFormOrigin" @update:submit="submitAdded" />
    </a-drawer>

    <!-- drawer for edit -->
    <a-drawer width="650" :title="$t('task.form.edit.title')" :visible="editFormVisible" @close="closeEditFrom">
      <EditTask :origin="editFormOrigin" @update:submit="submitEdited" />
    </a-drawer>

    <!-- drawer for search -->
    <a-drawer width="500" :title="$t('task.form.search.title')" :visible="searchFormVisible" @close="closeSearchForm">
      <SearchTask :origin="searchFormOrigin" @update:close="closeSearchForm" @update:submit="submitSearchForm" />
    </a-drawer>

    <!-- task list -->
    <div class="table-list">
      <a-table
        rowKey="id"
        :scroll="{ x: 3000, y: 1500 }"
        :columns="taskColumns"
        :data-source="taskList"
        :loading="taskLoading"
        :pagination="taskPagination"
        @change="loadTaskPagination"
      >
        <div slot="title" slot-scope="item">
          <div class="ellipsis">{{ item.title }}</div>
        </div>
        <div slot="status" slot-scope="item">
          <div v-if="item.status === 0">
            <span class="status-disabled">
              <a-icon type="warning" />
              {{ $t('task.status.disabled') }}
            </span>
          </div>
          <div v-if="item.status === 1">
            <span class="status-enabled">
              <a-icon type="check" />
              {{ $t('task.status.enabled') }}
            </span>
          </div>
        </div>
        <div slot="store" slot-scope="item">
          <div v-if="item.store === 1">
            <a-tooltip :title="$t('task.store.tips')" >
              <a-icon type="check" />
              {{ $t('task.store.enabled') }}
            </a-tooltip>
          </div>
        </div>
        <div slot="delay_seconds" slot-scope="item">
          <div v-if="item.delay_seconds > 0">
            <a-tooltip :title="$t('task.delay.seconds.tips', {delay: item.delay_seconds})">
              <a-icon type="check" />
              {{ item.delay_seconds }}
            </a-tooltip>
          </div>
        </div>
        <div slot="condition_expression" slot-scope="item">
          <div v-if="item.condition_expression !== ''">
            <a-tooltip :title="item.condition_expression" >
              <a-icon type="check"/>
              {{ $t('task.condition.expression.configured') }}
            </a-tooltip>
          </div>
        </div>
        <div slot="handler" slot-scope="item">
          <div class="ellipsis">
            <a-tooltip :title="item.handler">{{ item.handler }}</a-tooltip>
          </div>
        </div>
        <div slot="handler_response_expression" slot-scope="item">
          <div v-if="item.handler_response_expression !== ''">
            <a-tooltip :title="item.handler_response_expression" >
              <a-icon type="check"/>
              {{ $t('task.response.expression.configured') }}
            </a-tooltip>
          </div>
        </div>
        <div slot="failed" slot-scope="item">
          <div v-if="item.failed !== ''">
            <a-tooltip :title="$t('task.failed.tips', {handler: item.failed})" >
              <a-icon type="check"/>
              {{ $t('task.failed.configured') }}
            </a-tooltip>
          </div>
        </div>
        <div slot="succeed" slot-scope="item">
          <div v-if="item.succeed !== ''">
            <a-tooltip :title="$t('task.succeed.tips', {handler: item.succeed})" >
              <a-icon type="check"/>
              {{ $t('task.succeed.configured') }}
            </a-tooltip>
          </div>
        </div>
        <div slot="action" slot-scope="item" class="action-list">
          <router-link :to="{ name: 'ScheduleMessages', query: { task_id: item.id } }">
            <a-icon type="message" />
            {{ $t('action.message') }}
          </router-link>
          <a-divider type="vertical"/>
          <a v-if="item.status === 0" @click="openConfirmEnable(item)">
            <a-icon type="check" />
            {{ $t('action.enable') }}
          </a>
          <a v-if="item.status === 1" @click="openConfirmDisable(item)">
            <a-icon type="warning" />
            {{ $t('action.disable') }}
          </a>
          <a-divider type="vertical"/>
          <a @click="openEditFrom(item)">
            <a-icon type="edit" />
            {{ $t('action.edit') }}
          </a>
        </div>
      </a-table>
    </div>
  </page-header-wrapper>
</template>

<script>
import AddTask from './Add.vue'
import EditTask from './Edit.vue'
import SearchTask from './Search.vue'

import { disableTask, enableTask, getTaskPaging } from '@/api/v1'
import { Modal } from 'ant-design-vue'

export default {
  components: { AddTask, EditTask, SearchTask },
  computed: { params () { return this.$route.query } },
  created () {
    const params = this.params
    // Collect task filter conditions from query string.
    if (params.topic !== null && params.topic !== '') { this.taskConditions.topic = params.topic }
    if (params.tag !== null && params.tag !== '') { this.taskConditions.tag = params.tag }
    if (params.status !== null && params.status !== '') { this.taskConditions.status = params.status }
    if (params.handler !== null && params.handler !== '') { this.taskConditions.handler = params.handler }
    // Load task with default conditions.
    this.loadTask()
  },
  data () {
    return {
      addFormOrigin: {},
      addFormVisible: false,
      editFormOrigin: {},
      editFormVisible: false,
      modal: null,
      modalOption: {
        cancelText: this.$t('action.close'),
        centered: true,
        destroyOnClose: true,
        okText: this.$t('action.ok'),
        okType: 'warning',
        parentContext: this
      },
      searchFormOrigin: {},
      searchFormVisible: false,
      taskConditions: { topic: '', tag: '', status: '', handler: '', page: 1, size: 25 },
      taskColumns: [
        { key: 'id', title: '#', dataIndex: 'id', width: '60px', fixed: 'left' },
        { key: 'title', title: this.$t('task.title'), scopedSlots: { customRender: 'title' }, width: '300px', fixed: 'left' },
        { key: 'status', title: this.$t('task.status'), scopedSlots: { customRender: 'status' }, width: '100px', fixed: 'left' },
        { key: 'store', title: this.$t('task.store'), scopedSlots: { customRender: 'store' } },
        { key: 'topic', title: this.$t('task.topic'), dataIndex: 'topic' },
        { key: 'tag', title: this.$t('task.tag'), dataIndex: 'tag' },
        { key: 'condition_expression', title: this.$t('task.condition.expression'), scopedSlots: { customRender: 'condition_expression' } },
        { key: 'delay_seconds', title: this.$t('task.delay.seconds'), scopedSlots: { customRender: 'delay_seconds' } },
        { key: 'handler', title: this.$t('task.handler'), scopedSlots: { customRender: 'handler' }, width: '300px' },
        { key: 'handler_format', title: this.$t('task.handler.format'), dataIndex: 'handler_format' },
        { key: 'handler_method', title: this.$t('task.handler.method'), dataIndex: 'handler_method' },
        { key: 'threads', title: this.$t('task.threads'), dataIndex: 'threads' },
        { key: 'concurrency', title: this.$t('task.concurrency'), dataIndex: 'concurrency' },
        { key: 'max_retry', title: this.$t('task.max.retry'), dataIndex: 'max_retry' },
        { key: 'handler_timeout', title: this.$t('task.handler.timeout'), dataIndex: 'handler_timeout' },
        { key: 'response_format', title: this.$t('task.response.format'), dataIndex: 'handler_response_format' },
        { key: 'handler_response_expression', title: this.$t('task.response.expression'), scopedSlots: { customRender: 'handler_response_expression' } },
        { key: 'failed', title: this.$t('task.failed'), scopedSlots: { customRender: 'failed' } },
        { key: 'succeed', title: this.$t('task.succeed'), scopedSlots: { customRender: 'succeed' } },
        { key: 'action', title: '', scopedSlots: { customRender: 'action' }, width: '220px', fixed: 'right' }
      ],
      taskList: [],
      taskLoading: false,
      taskPagination: { current: 0, pageSize: 0, total: 0 }
    }
  },
  methods: {
    closeAddFrom () { this.addFormVisible = false },
    closeEditFrom () { this.editFormVisible = false },
    closeSearchForm () { this.searchFormVisible = false },
    createModal (opt) {
      if (this.modal !== null) {
        this.modal.destroy()
      }
      this.modal = Modal.confirm(opt)
    },

    async loadTask () {
      this.taskLoading = true
      getTaskPaging(
        this.taskConditions, (res) => {
          // Fill with response list.
          this.taskList = res.data.body
          // Fill pagination.
          this.taskPagination.current = res.data.paging.curr
          this.taskPagination.pageSize = res.data.paging.size
          this.taskPagination.total = res.data.paging.total
          // Condition filters.
          this.taskConditions.page = this.taskPagination.current
          this.taskConditions.size = this.taskPagination.pageSize
        }, () => {}, () => {
          this.taskLoading = false
        }
      )
    },

    loadTaskPagination (p) {
      this.taskPagination = p
      this.taskConditions.page = this.taskPagination.current
      this.taskConditions.size = this.taskPagination.pageSize
      this.loadTask()
    },

    openAddForm () { this.addFormVisible = true },
    openConfirmDisable (item) {
      const opt = this.modalOption
      opt.title = this.$t('task.confirm.disable')
      opt.content = this.$t('task.confirm.disable.message', { title: item.title })
      opt.onOk = () => { this.sendDisable(item) }
      this.createModal(opt)
    },
    openConfirmEnable (item) {
      const opt = this.modalOption
      opt.title = this.$t('task.confirm.enable')
      opt.content = this.$t('task.confirm.enable.message', { title: item.title })
      opt.onOk = () => { this.sendEnable(item) }
      this.createModal(opt)
    },
    openEditFrom (item) { this.editFormOrigin = item; this.editFormVisible = true },
    openSearchForm () { this.searchFormOrigin = this.taskConditions; this.searchFormVisible = true },

    async sendDisable (item) {
      this.clusterLoading = true
      disableTask({ id: item.id }, () => {
        this.$message.info(this.$t('task.confirm.disable.succeed', { title: item.title }))
        this.clusterLoading = false
        this.loadTask()
      }, (err) => {
        this.clusterLoading = false
        this.$message.error(err)
      })
    },
    async sendEnable (item) {
      this.clusterLoading = true
      enableTask({ id: item.id }, () => {
        this.$message.info(this.$t('task.confirm.enable.succeed', { title: item.title }))
        this.clusterLoading = false
        this.loadTask()
      }, (err) => {
        this.clusterLoading = false
        this.$message.error('' + err)
      })
    },

    submitAdded () { this.loadTask(); this.closeAddFrom() },
    submitEdited () { this.loadTask(); this.closeEditFrom() },
    submitSearchForm (v) { this.taskConditions = v; this.loadTask(); this.closeSearchForm() }
  }
}
</script>
